package org.tlipoca.smsteamplayer.service.impl;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.genntii.smcommon.constant.SteamApiURLConstant;
import org.genntii.smcommon.constant.SteamConstant;
import org.genntii.smcommon.utils.HttpClientUtil;
import org.genntii.smdomain.entity.SteamPlayer;
import org.genntii.smdomain.entity.SteamPlayerImage;
import org.genntii.smdomain.entity.SteamPlayerImageResult;
import org.genntii.smdomain.entity.SteamPlayerResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.tlipoca.smsteamplayer.client.SteamUserStoreClient;
import org.tlipoca.smsteamplayer.mapper.SteamPlayerMapper;
import org.tlipoca.smsteamplayer.service.SteamPlayerService;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class SteamPlayerServiceImpl extends ServiceImpl<SteamPlayerMapper, SteamPlayer> implements SteamPlayerService {

    @Resource
    private SteamUserStoreClient steamUserStoreClient;

    @Autowired
    private SteamPlayerMapper steamPlayerMapper;

    @Override
    public SteamPlayer getSteamPlayerBySteamidService(String  steamid) {

        Long steamId = Long.valueOf(steamid);

        // 查询数据库是否存在该Steam用户
        SteamPlayer steamPlayer = steamPlayerMapper.selectBySteamid(steamId);
        if(steamPlayer == null) {
            // 若不存在 则查询Steam接口获取数据
            log.info("不存在用户 SteamId: {}, 开始获取数据",steamid);
            return getSteamPlayer(steamId, 50);
        }

//        // 存在则判断更新时间是否大于一天
//        if(steamPlayer.getUpdateTime().plusHours(24L).isBefore(LocalDateTime.now())) {
//            // 更新时间大于一天 尝试更新用户信息
//            log.info("用户信息更新时间大于一天 尝试更新用户信息");
//            try{
//                SteamPlayer steamPlayer1 = getSteamPlayer(steamId, 3);
//                steamPlayer1 = getSteamPlayerImageBySteamidService(steamId,3,steamPlayer1);
//                return steamPlayer1;
//            }
//            catch (Exception e) {
//                log.info("尝试更新用户信息失败 返回数据库内用户信息");
//                return steamPlayer;
//            }
//
//        }

//        steamUserStoreClient.getSteamUserStoreBySteamId(steamId);
        // 用户存在且更新时间小于一天则返回
        return steamPlayer;
    }

    private SteamPlayer getSteamPlayer(Long steamid, Integer maxRetries) {
        Map<String, Object> map = Map.of("key", SteamConstant.STEAM_KEY, "steamids", steamid);

        JSONObject jsonResult = (JSONObject) JSON.parseObject(HttpClientUtil.doGetWithRetry(SteamApiURLConstant.GET_USER_SUMMARIES, map, maxRetries)).get("response");
        SteamPlayerResult steamPlayerResult = JSON.parseArray(jsonResult.get("players").toString(), SteamPlayerResult.class).get(0);
        log.info("获取用户信息成功");

        SteamPlayer steamPlayer = new SteamPlayer();
        BeanUtils.copyProperties(steamPlayerResult,steamPlayer);

        log.info("开始同步个人头像背景信息");
        steamPlayer = getSteamPlayerImageBySteamidService(steamid,maxRetries,steamPlayer);

        log.info("开始更新Mysql...");
        if (steamPlayerMapper.selectBySteamid(Long.valueOf(steamid))!=null ){
            steamPlayerMapper.updateById(steamPlayer);
        }else steamPlayerMapper.insert(steamPlayer);

        return steamPlayer;
    }

    public SteamPlayer getSteamPlayerImageBySteamidService(Long steamid, Integer maxRetries,SteamPlayer steamPlayer) {
        Map<String, Object> map = Map.of("key", SteamConstant.STEAM_KEY, "steamid", steamid);

        JSONObject jsonObject = (JSONObject) JSON.parseObject(HttpClientUtil.doGetWithRetry(SteamApiURLConstant.GET_USER_IMAGE, map, maxRetries)).get("response");
        String profileBackgroundImage = SteamApiURLConstant.IMAGE_PRE + ((HashMap.Entry)((com.alibaba.fastjson2.JSONObject)((HashMap.Entry)jsonObject.entrySet().toArray()[0]).getValue()).entrySet().toArray()[1]).getValue().toString();
        System.out.println(profileBackgroundImage);
        String miniProfileBackground = SteamApiURLConstant.IMAGE_PRE + ((HashMap.Entry)((com.alibaba.fastjson2.JSONObject)((HashMap.Entry)jsonObject.entrySet().toArray()[1]).getValue()).entrySet().toArray()[1]).getValue().toString();
        String avatarFrame = SteamApiURLConstant.IMAGE_PRE + ((HashMap.Entry)((com.alibaba.fastjson2.JSONObject)((HashMap.Entry)jsonObject.entrySet().toArray()[2]).getValue()).entrySet().toArray()[2]).getValue().toString();
        String animatedAvatar = SteamApiURLConstant.IMAGE_PRE + ((HashMap.Entry)((com.alibaba.fastjson2.JSONObject)((HashMap.Entry)jsonObject.entrySet().toArray()[3]).getValue()).entrySet().toArray()[2]).getValue().toString();

        steamPlayer.setProfileBackgroundImageLarge(profileBackgroundImage);
        steamPlayer.setAvatarFrameImageLarge(avatarFrame);
        steamPlayer.setMiniProfileBackgroundImageLarge(miniProfileBackground);
        steamPlayer.setAnimatedAvatarImageLarge(animatedAvatar);
        return steamPlayer;
    }
}
